# -*- coding:utf-8 -*-
"""
@Time : 2025/02/11 17:34 PM
@Author: xiaomi
@Des: 认证
"""

from core.Auth import create_access_token
from fastapi.security.oauth2 import OAuth2PasswordRequestForm
from fastapi import Depends, HTTPException, status
from models.base import User
from core.Utils import check_password
# 系统包
from fastapi import Request, APIRouter, Query, Security
from core.Auth import check_permissions
from core.Response import fail, success
from core.Utils import code_number
from models.base import User

router = APIRouter()
@router.post("/authorize")
async def authorize(data: OAuth2PasswordRequestForm = Depends()):
    # 验证用户是否存在
    user_data = await User.get_or_none(username=data.username)
    if not user_data:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"用户{data.username}密码验证失败!",
            headers={"WWW-Authenticate": "Bearer"},
        )
    if not user_data.password:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"用户{data.username}密码验证失败!",
            headers={"WWW-Authenticate": "Bearer"},
        )
    if not check_password(data.password, user_data.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"用户{data.username}密码验证失败!",
            headers={"WWW-Authenticate": "Bearer"},
        )
    if not user_data.user_status:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=f"用户{data.username}已被管理员禁用!",
            headers={"WWW-Authenticate": "Bearer"},
        )
    access_token = create_access_token(data={"user_id": user_data.id, "user_type": user_data.user_type})
    return {"access_token": access_token, "token_type": "bearer"}
